package org.cobo.vmmanagement.web;
import java.util.Iterator;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.cobo.vmmanagement.constant.CategoryType;
import org.cobo.vmmanagement.domain.Charge;
import org.cobo.vmmanagement.domain.Project;
import org.cobo.vmmanagement.domain.RateToARS;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@RequestMapping("/projectsummary/**")
@Controller
public class ProjectSummaryController {

    @RequestMapping(value="/projectsummary/project/{projectId}", method = RequestMethod.GET)
    public String get(@PathVariable Long projectId, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
    	// Get project
		return this.post(projectId, modelMap, request, response);
    }
    
	@RequestMapping(method = RequestMethod.POST)
    public String post(@RequestParam("projectId") Long projectId, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
		
		// Get project
		Project project = Project.findProject(projectId);
		
		// Get currency rate
		Double rate = project.getRateToARS().getRate();
		
		// Calculate budget 
		if(project.getQuotedHours() == null) {
			project.setBudget(new Double(0));
		} else {
			Double budget = project.getQuotedHours().doubleValue() * project.getQuotedRate().doubleValue() * rate;
			project.setBudget(budget);
		}
		
		// Calculate total amount
		Double expenses = (double) 0;
		if(project.getExpenses() != null) {
			expenses = project.getExpenses();
		}
		Double totalAmount = project.getBudget() + (expenses * rate);
		project.setTotalAmount(totalAmount);
		
		// Get charged hours detail
		int consultantHours = 0;
		int seniorHours = 0;
		int managerHours = 0;
		int seniorManagerHours = 0;
		int partnerHours = 0;
		int qaPartnerHours = 0;
		int totalHours = 0;
		int totalTariff = 0;
		TypedQuery<Charge> discriminatedChargedHours = Charge.findChargesByProject(project);
		Iterator<Charge> iterator = discriminatedChargedHours.getResultList().iterator();
		while(iterator.hasNext()) {
			Charge tempCharge = iterator.next();
			int hours = tempCharge.getAmountOfHours().intValue();
			totalHours += hours;
			totalTariff += hours * tempCharge.getResource().getCategory().getHourlyRate();
			String category = tempCharge.getResource().getCategory().getName();
			// TODO: parametrize categories
			if(category.equals("Consultant")) {
				consultantHours += hours;
			} else if(category.equals("SeniorConsultant")) {
				seniorHours += hours;
			} else if(category.equals("Manager")) {
				managerHours += hours;
			} else if(category.equals("SeniorManager")) {
				seniorManagerHours += hours;
			} else if(category.equals("Partner")) {
				partnerHours += hours;
			} else if(category.equals("QAPartner")) {
				qaPartnerHours += hours;
			} else {
				// TODO: Error?
				//totalHours -= hours;
			}	
		}
		
		// Set charged hours
		project.setChargedHours(totalHours);
				
		//Calculate hourly cost and return TODO: Parametrize HourlyTariff
		if(totalHours == 0) {
			project.setReturnPercentage(new Double(0));
			project.setHourlyCost(new Double(0));
		} else {
			Double hourlyCost = project.getBudget().doubleValue() / totalHours;
			project.setHourlyCost(hourlyCost);
			double hourlyTariff = totalTariff / totalHours;
			Double returnPercentage = project.getHourlyCost().doubleValue() / hourlyTariff;
			project.setReturnPercentage(returnPercentage);
		}
		
		project.merge();
		
		// Get current user role
		String role = SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString();
		boolean isManager = role.contains("ROLE_MANAGER") || role.contains("ROLE_ADMIN") ? true : false;
		
		modelMap.addAttribute("isManager", isManager);
		modelMap.addAttribute("project", project);
		return "projectsummary/summary";
	}

    @RequestMapping
    public String index(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
    	return "projectsummary/index";
    }
    
    @RequestMapping(method = RequestMethod.GET)
    public String get(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
    	List<Project> projects = Project.findAllProjects();
		// Get current user role
		String role = SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString();
		boolean isManager = role.contains("ROLE_MANAGER") || role.contains("ROLE_ADMIN") ? true : false;
		
		modelMap.addAttribute("isManager", isManager);
    	modelMap.addAttribute("projects", projects);
    	
    	return "projectsummary/index";
    }
}
